package cn.newgrand.netcall.ui.questionRecord;

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.TitlePanel;

import cn.newgrand.netcall.util.StringUtil;
import cn.newgrand.smackx.attachmenttransfer.FileTransferManager;
import cn.newgrand.smackx.specialist.ExpertManager;
import cn.newgrand.smackx.specialist.packet.QuestionRecordIQ;

public class QuestionRecordEditor {
	
	private QuestionBaseInfoPanel questionBaseInfoPanel;
	private QuestionDescriptionPanel questionDescriptionPanel;
	private AttachmentPanel attachmentPanel;
	private String questionRecordId;
	public QuestionRecordEditor(FileTransferManager fileTransferManager){
		final JTabbedPane tabbedPane = new JTabbedPane();
		
		questionBaseInfoPanel = new QuestionBaseInfoPanel();
		tabbedPane.add("基本信息",questionBaseInfoPanel);
		
		questionDescriptionPanel = new QuestionDescriptionPanel();
		tabbedPane.add("问题描述",questionDescriptionPanel);
		
		questionRecordId = StringUtil.getPrimaryKey();
		attachmentPanel = new AttachmentPanel(questionRecordId,fileTransferManager);
		
		tabbedPane.add("附件",attachmentPanel);
		
		final JOptionPane pane;
        final JDialog dlg;

        TitlePanel titlePanel;

        ImageIcon icon = null;
        if (icon == null) {
            icon = SparkRes.getImageIcon(SparkRes.BLANK_24x24);
        }

        // Create the title panel for this dialog
        titlePanel = new TitlePanel("记录未解决的问题信息", Res.getString("message.save.profile"), icon, true);

        // Construct main panel w/ layout.
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // The user should only be able to close this dialog.
        Object[] options = {Res.getString("save"), Res.getString("cancel")};
        pane = new JOptionPane(tabbedPane, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);

        mainPanel.add(pane, BorderLayout.CENTER);

        JOptionPane p = new JOptionPane();
        dlg = p.createDialog(SparkManager.getWorkspace(), "未解决问题记录");
        dlg.setModal(false);

        dlg.pack();
        dlg.setSize(588, 500);
        dlg.setResizable(true);
        dlg.setContentPane(mainPanel);
        dlg.setLocationRelativeTo(SparkManager.getWorkspace());

        PropertyChangeListener changeListener = new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
                String value = (String)pane.getValue();
                if (Res.getString("cancel").equals(value)) {
                    pane.removePropertyChangeListener(this);
                    dlg.dispose();
                }
                else if (Res.getString("save").equals(value)) {
                    if(isvalidInfo()){
                    	pane.removePropertyChangeListener(this);
                    	saveQuestionDescription();
                    	dlg.dispose();
                    }else{
                    	pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
                    }
                }
            }

        };

        pane.addPropertyChangeListener(changeListener);
        dlg.setVisible(true);
        dlg.toFront();
        dlg.requestFocus();

	}
	
	private boolean isvalidInfo() {
		String askername = questionBaseInfoPanel.getAskerNameField().getText().trim();
		String askertruename = questionBaseInfoPanel.getTrueNameField().getText().trim();
		String company = questionBaseInfoPanel.getCompanyField().getText().trim();
		String department = questionBaseInfoPanel.getDepartmentField().getText().trim();
		String hometelephone = questionBaseInfoPanel.getHomePhoneField().getText().trim();
		String persontelephone = questionBaseInfoPanel.getTelephoneField().getText().trim();
		String facsimile = questionBaseInfoPanel.getFacsimileField().getText().trim();
		String email = questionBaseInfoPanel.getEmailField().getText().trim();
		//String remark = questionBaseInfoPanel.getRemarkArea().getText().trim();
		String product = questionDescriptionPanel.getProductField().getSelectedItem().toString().trim();
		String version = questionDescriptionPanel.getVersionField().getText().trim();
		String applyserver = questionDescriptionPanel.getApplyServerField().getText().trim();
		String databaseserver = questionDescriptionPanel.getDatabaseServerField().getText().trim();
		String databaseversion = questionDescriptionPanel.getDatabaseVserionField().getText().trim();
		String databasetype = questionDescriptionPanel.getDatabaseTypeField().getText().trim();
		String questiondescription = questionDescriptionPanel.getQuestionDescriptionArea().getText().trim();
		//String primeopinion = questionDescriptionPanel.getPrimeReasonArea().getText().trim();
		if("".equals(askername)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "咨询者不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionBaseInfoPanel.getAskerNameField().requestFocus();
			return false;
		}
		if("".equals(askertruename)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "姓名不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionBaseInfoPanel.getTrueNameField().requestFocus();
			return false;
		}
		if("".equals(company)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "公司不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionBaseInfoPanel.getCompanyField().requestFocus();
			return false;
		}
		if("".equals(department)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "部门不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionBaseInfoPanel.getDepartmentField().requestFocus();
			return false;
		}
		if("".equals(hometelephone)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "套件不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionBaseInfoPanel.getHomePhoneField().requestFocus();
			return false;
		}
		if("".equals(persontelephone)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "手机不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionBaseInfoPanel.getTelephoneField().requestFocus();
			return false;
		}
		if("".equals(facsimile)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "传真不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionBaseInfoPanel.getFacsimileField().requestFocus();
			return false;
		}
		if("".equals(email)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "邮箱不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionBaseInfoPanel.getEmailField().requestFocus();
			return false;
		}else{
			String regex="[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9]+(\\.(com|cn|org|edu|hk))";
			if(!email.matches(regex)){
				JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "邮箱格式不合法", "警告对话框", JOptionPane.WARNING_MESSAGE);
				questionBaseInfoPanel.getEmailField().requestFocus();
				return false;
			}
		}
		if("".equals(product)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "产品不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionDescriptionPanel.getProductField().requestFocus();
			return false;
		}
		if("".equals(version)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "版本不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionDescriptionPanel.getVersionField().requestFocus();
			return false;
		}
		if("".equals(applyserver)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "应用服务器不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionDescriptionPanel.getApplyServerField().requestFocus();
			return false;
		}if("".equals(databaseserver)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "数据库服务器不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionDescriptionPanel.getDatabaseServerField().requestFocus();
			return false;
		}
		if("".equals(databasetype)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "数据库类型不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionDescriptionPanel.getDatabaseTypeField().requestFocus();
			return false;
		}
		if("".equals(databaseversion)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "数据库版本不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionDescriptionPanel.getDatabaseVserionField().requestFocus();
			return false;
		}
		if("".equals(questiondescription)){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "问题描述不能为空", "警告对话框", JOptionPane.WARNING_MESSAGE);
			questionDescriptionPanel.getQuestionDescriptionArea().requestFocus();
			return false;
		}
		return true;
	}
	
	/**
	 * 取出未解决问题的信息,并保存到数据库中
	 */
	public void saveQuestionDescription(){
		QuestionRecordIQ questionIQ = new QuestionRecordIQ();
		questionIQ.setType(IQ.Type.SET);
		questionIQ.setTo(ExpertManager.SERVICE + SparkManager.getConnection().getServiceName());
		questionIQ.setQuestionrecordid(questionRecordId);
		String askername = questionBaseInfoPanel.getAskerNameField().getText().trim();
		questionIQ.setAskername(askername);
		String askertruename = questionBaseInfoPanel.getTrueNameField().getText().trim();
		questionIQ.setAskertruename(askertruename);
		String company = questionBaseInfoPanel.getCompanyField().getText().trim();
		questionIQ.setCompany(company);
		String department = questionBaseInfoPanel.getDepartmentField().getText().trim();
		questionIQ.setDepartment(department);
		String hometelephone = questionBaseInfoPanel.getHomePhoneField().getText().trim();
		questionIQ.setProductsuit(hometelephone);
		String persontelephone = questionBaseInfoPanel.getTelephoneField().getText().trim();
		questionIQ.setPersontelephone(persontelephone);
		String facsimile = questionBaseInfoPanel.getFacsimileField().getText().trim();
		questionIQ.setFacsimile(facsimile);
		String email = questionBaseInfoPanel.getEmailField().getText().trim();
		questionIQ.setEmail(email);
		String remark = questionBaseInfoPanel.getRemarkArea().getText().trim();
		questionIQ.setRemark(remark);
		String product = questionDescriptionPanel.getProductField().getSelectedItem().toString().trim();
		questionIQ.setProduct(product);
		String version = questionDescriptionPanel.getVersionField().getText().trim();
		questionIQ.setVersion(version);
		String applyserver = questionDescriptionPanel.getApplyServerField().getText().trim();
		questionIQ.setApplyserver(applyserver);
		String databaseserver = questionDescriptionPanel.getDatabaseServerField().getText().trim();
		questionIQ.setDatabaseserver(databaseserver);
		String databaseversion = questionDescriptionPanel.getDatabaseVserionField().getText().trim();
		questionIQ.setDatabaseversion(databaseversion);
		String databasetype = questionDescriptionPanel.getDatabaseTypeField().getText().trim();
		questionIQ.setDatabasetype(databasetype);
		String questiondescription = questionDescriptionPanel.getQuestionDescriptionArea().getText().trim();
		questionIQ.setQuestiondescription(questiondescription);
		String primeopinion = questionDescriptionPanel.getPrimeReasonArea().getText().trim();
		questionIQ.setPrimeopinion(primeopinion);
		final PacketCollector collector = SparkManager.getConnection().createPacketCollector(new PacketIDFilter(questionIQ.getPacketID()));
		SparkManager.getConnection().sendPacket(questionIQ);
		QuestionRecordIQ result = (QuestionRecordIQ)collector.nextResult(5000);
		collector.cancel();
		if(result == null || result.getError() != null){
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "记录失败", Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
		}else{
			JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "记录成功", Res.getString("title.success"), JOptionPane.INFORMATION_MESSAGE);
		}
	}
	
}
